import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {BaseService} from "../../../shared/service/base.service";
import {validMoney} from "../../../shared/validator/validator";
import {ApiUrl} from "../../../config/api-url";

@Component({
  selector: 'app-maintenance-replace',
  templateUrl: './maintenance-replace.component.html',
  styleUrls: ['./maintenance-replace.component.less']
})
export class MaintenanceReplaceComponent implements OnInit {
  @Input()
  maintenanceAndReplaceShow = false;
  @Input()
  data: any;
  // 父子互传值
  @Output()
  emit: EventEmitter<any> = new EventEmitter();
  // 父子互传值
  @Output()
  ok: EventEmitter<any> = new EventEmitter();
  // 提交时提交按钮是否加载中
  isOkLoading: any;
  // 模态框表单
  formModel: FormGroup;
  netCardReplaceStatus: any;
  deviceId: any;
  constructor(private fb: FormBuilder, public baseService: BaseService) {
  }

  ngOnInit(): void {
    this.buildForm();
  }

  ngOnChanges() {
    const _this = this;
    if (this.data != null) {
      this.deviceId = this.data.id;
      this.netCardReplaceStatus = this.data.netCardReplaceStatus;
      if (this.netCardReplaceStatus == 2) {
        _this.formModel.get('deviceNo')!.setValidators(Validators.required);
        _this.formModel.get('deviceNo')!.markAsDirty();
        _this.formModel.get('deviceNo')!.updateValueAndValidity();
      }
    }
  }

  buildForm() {
    this.formModel = this.fb.group({
      deviceNo: [null,],
    });
  }

  // 取消
  handleCancel() {
    console.log("是否进入")
    this.maintenanceAndReplaceShow = false;
    this.data = null;
    this.formModel.reset({
      deviceNo: null,
    });
    this.emit.emit(false);
  }

  // 确认
  handleOk() {
    this.isOkLoading = true;
    if (!this.baseService.zorro.validateFormValidate(this.formModel)) {
      this.isOkLoading = false;
      return;
    }
    let body = {
      newDeviceNo: this.formModel.controls.deviceNo.value,
      id: this.deviceId,
      status: 5,
    };
    this.baseService.put(ApiUrl.DeviceUrl + '/updateMaintainDevice', body).subscribe(
      data => {
        if (data.status == 0) {
          this.baseService.layer.messageSuccess('修改成功！');
          this.data = null;
          this.maintenanceAndReplaceShow = false;
          this.formModel.reset({
            deviceNo: null,
          });
          this.isOkLoading = false;
          this.ok.emit(false);

        } else {
          this.isOkLoading = false;
          this.baseService.layer.messageError('修改失败：' + data.msg);
        }
      }
    );
    // }
    // });
    // this.data['newDeviceNo'] = this.formModel.controls["deviceNo"].value;
    // this.ok.emit(this.data);
  }

}
